<template>
    <div>
        <el-button type="success" @click="AddUrlProduction">新增</el-button>
        <el-button type="primary" @click="ExcelProduction">导出</el-button>
        <el-button @click="handleImport">导入</el-button>
        <br>
        <br>
        <!-- 查询条件部分 -->
        <div class="search-section">
            <el-form :inline="true" :model="prolist">
                <el-form-item label="关联项目">
                    <el-input v-model="prolist.AssociatedItemNumber" placeholder="输入关联项目"></el-input>
                </el-form-item>
                <el-form-item label="生成订单状态">
                    <el-select v-model="prolist.AutomaticOrderGeneration" placeholder="请选择">
                        <el-option value="false">已生成</el-option>
                        <el-option value="true">未生成</el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="计划编号">
                    <el-input v-model="prolist.DocumentNo" placeholder="输入计划编号"></el-input>
                </el-form-item>
                <el-form-item label="添加人员">
                    <el-input v-model="prolist.DocumentMaker" placeholder="请选择或输入"></el-input>
                </el-form-item>
                <el-form-item label="添加日期">
                    <el-date-picker v-model="prolist.DocumentationFriDate" type="date" placeholder="选择日期"></el-date-picker>-
                    <el-date-picker v-model="prolist.DocumentationEndDate" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="计划主题">
                    <el-input v-model="prolist.DocumentSubject" placeholder="输入计划主题"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="GetProductionPlanning">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <span style="font-size: 20px; margin-left: 20px; font-weight: bold">生产计划列表</span>
        
  <input ref="fileInput" type="file" style="display: none" @change="handleFileChange" />
        <!-- 生产计划列表（仅展示序号列相关结构） -->
        <div class="table-container">
            <el-table :data="planList" stripe ref="tableRef" height="300">
                <el-table-column>
                    <template #header>
                        <el-checkbox v-model="allChecked" @change="handleCheckAllChange"></el-checkbox>
                    </template>
                    <template #default="scope">
                        <el-checkbox v-model="checkedIds" :label="scope.row.productionPlanningId"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column prop="productionPlanningId" label="主键"></el-table-column>
                <el-table-column prop="documentNo" label="生产计划编号">
                    <template #default="scope">
                {{ scope.row.documentNo }}
            </template>
                </el-table-column>
                <el-table-column prop="documentSubject" label="生产计划主题"></el-table-column>
                <el-table-column prop="associatedItemNumber" label="关联项目"></el-table-column>
                <!-- <el-table-column prop="id" label="本次生产计划数量"></el-table-column>
                <el-table-column prop="id" label="已下订单数量"></el-table-column> -->
                <el-table-column prop="automaticOrderGeneration" label="生产订单状态">
                    <template #default="scope">
                        {{ scope.row.automaticOrderGeneration ? '未生成' : '已生成'}}
                    </template>
                </el-table-column>
                <el-table-column prop="documentMaker" label="制单人员"></el-table-column>
                <el-table-column prop="documentationDate" label="制单日期">
                    <template #default="scope">
                {{ scope.row.documentationDate ? (new Date(scope.row.documentationDate).getFullYear() + '年' + String(new Date(scope.row.documentationDate).getMonth() + 1).padStart(2, '0') + '月' + String(new Date(scope.row.documentationDate).getDate()).padStart(2, '0') + '日') : '' }}
            </template>
                </el-table-column>
                <el-table-column prop="productionPlanningId" label="操作">
                    <template #default="scope">
                        <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.productionPlanningId)">编辑</el-button>
                        <el-button type="text" @click="DeleteProductionPlanning(scope.row.productionPlanningId)">删除</el-button>
                        <!-- <el-button type="text" @click="GetProductionPlanningDetail(scope.row.productionPlanningId)">查看详情</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <el-button @click="batchDelete">批量删除</el-button>
        </div>
        <!-- 分页部分 -->
        <div class="demo-pagination-block">
            <el-pagination
                v-model:current-page="page.PageIndex"
                v-model:page-size="page.PageSize"
                :page-sizes="[10, 20, 30, 50]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { read, write } from '@/axios/axiosHelper';
import { ElMessage, ElMessageBox } from 'element-plus';
import router from '@/router';

// 定义分页对象
const page = ref({
    PageIndex: 1,
    PageSize: 50,
});

// 定义搜索表单数据
const prolist = ref({
    DocumentSubject: '',
    DocumentNo: '',
    AssociatedItemNumber: '',
    AutomaticOrderGeneration: '',
    DocumentMaker: '',
    DocumentationFriDate: '',
    DocumentationEndDate: '',
});

// 定义分页总数
const total = ref({
    totalCount: 0,
    totalPage: 0,
});

// 模拟生产计划列表数据
const planList = ref([
    {
        "id": 1,
        "productionPlanningId": '',
        "documentSubject": "",
        "documentNo": "",
        "associatedItemNumber": "",
        "automaticOrderGeneration": '',
        "documentMaker": "",
        "documentationDate": "",
        "remark": "",
        "ordersId": '',
    }
]);

// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);
// 选中的 ID 列表
const checkedIds = ref([]);

// 查询方法
const search = () => {
    console.log('查询条件：', prolist.value);
    // 这里可以添加实际的查询逻辑
    GetProductionPlanning();
};

const GetProductionPlanning = () => {
    read.get('/z-read/api/Management/GetProduction', {
        params: {
            PageIndex: page.value.PageIndex,
            PageSize: page.value.PageSize,
            DocumentSubject: prolist.value.DocumentSubject,
            DocumentNo: prolist.value.DocumentNo,
            AssociatedItemNumber: prolist.value.AssociatedItemNumber,
            AutomaticOrderGeneration: prolist.value.AutomaticOrderGeneration,
            DocumentMaker: prolist.value.DocumentMaker,
            DocumentationFriDate: prolist.value.DocumentationFriDate,
            DocumentationEndDate: prolist.value.DocumentationEndDate,
        }
    }).then((res) => {
        planList.value = res.data.data.list;
        total.value.totalCount = res.data.data.totalCount;
        total.value.totalPage = res.data.data.totalPage;
        // 重置全选状态和选中的 ID 列表
        allChecked.value = false;
        checkedIds.value = [];
    });
};

const handleSizeChange = (val) => {
    page.value.PageSize = val;
    GetProductionPlanning();
};
const handleCurrentChange = (val) => {
    page.value.PageIndex = val;
    GetProductionPlanning();
};

onMounted(() => {
    GetProductionPlanning();
});

//跳转编辑页面
const GetBYIdProductionPlanning = (productionPlanningId) => {
    router.push({
        name: 'GetBYIdProductionPlanning',
        query: {
            productionPlanningId: productionPlanningId
        }
    });
    console.log(productionPlanningId);
};

//跳转详情页面
const GetProductionPlanningDetail=(productionPlanningId)=>{
    router.push({
        name: 'GetProductionPlanningDetailList',
        query: {
            productionPlanningId: productionPlanningId
        }
    });
    console.log(productionPlanningId);
}

// 删除单条记录
const DeleteProductionPlanning = async (productionPlanningId) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await write.post(
                `/z-write/api/Managerment/DelProduction`,
                {
                    ProductionPlanningIds: productionPlanningId.toString()
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除错误:', error);
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};

// 处理全选
const handleCheckAllChange = (value) => {
    if (value) {
        checkedIds.value = planList.value.map(item => item.productionPlanningId);
    } else {
        checkedIds.value = [];
    }
    allChecked.value = value;
};

// 批量删除
const batchDelete = async () => {
    if (checkedIds.value.length === 0) {
        ElMessage.warning('请选择要删除的记录');
        return;
    }
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除选中的记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const ids = checkedIds.value.join(',');
            const response = await write.post(
                `/z-write/api/Managerment/DelProduction`,
                {
                    ProductionPlanningIds: ids
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('批量删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`批量删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除错误:', error);
            ElMessage.error('批量删除失败，请检查网络或联系管理员');
        }
    }
};

//跳转添加计划页面
const AddUrlProduction = () => {
    router.push({
        name: 'AddProductionPlanning',
    });
}

//导出Excel表
const ExcelProduction=()=>{
    window.location.href='http://localhost:19786/api/Management/ExportToExcel';
}

//导入Excel表
const fileInput = ref(null);

const handleImport = () => {
  fileInput.value.click();
};

const handleFileChange = async (event) => {
  const files = event.target.files;
  if (files.length > 0) {
    const file = files[0];
    const formData = new FormData();
    formData.append('file', file); // 假设后端接口接收的文件参数名为 'file'

    try {
      const response = await write.post('/z-write/api/Managerment/ImportExcel', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('导入成功:', response.data);
    } catch (error) {
      console.error('导入失败:', error);
    }
  }
  // 清空输入框，以便下次选择相同文件时也能触发 change 事件
  fileInput.value.value = '';
  GetProductionPlanning();
};

</script>

<style scoped>
.search-section {
    margin-bottom: 20px;
}

.table-container {
    max-height: 400px; /* 固定表格最大高度 */
    overflow-y: auto; /* 超出高度显示滚动条 */
    margin-bottom: 20px; /* 为分页预留空间 */
}

.el-table {
    width: 100%; /* 表格宽度占满容器 */
}
</style>    